<template>
  <div>
    <!-- 第一行 -->
    <div class="header">
      <el-form :inline="true" :model="form" class="demo-form-inline">
        <el-form-item>
          <el-select clearable v-model="form.type" placeholder="请选择工单类型">
            <el-option label="维修" value="维修"></el-option>
            <el-option label="完好" value="完好"></el-option>
            <el-option label="损坏" value="损坏"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="toSearch">搜索</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="second">
      <el-table :data="deviceData" style="width: 100%">
        <el-table-column type="index" :index="1" label="序号" width="180" align="center">
        </el-table-column>
        <el-table-column prop="engineer_name" label="工程名称" width="180" align="center">
        </el-table-column>
        <el-table-column prop="device_name" label="设备名称" align="center">
        </el-table-column>
        <el-table-column prop="bill_why" label="问题叙述" align="center">
        </el-table-column>
        <el-table-column  prop="status" label="状态" align="center">
          <template v-slot="scope">
            <div>
              <el-tag v-if="scope.row.status == '已完成'" effect="dark" type="success">已完成</el-tag>
              <el-tag v-else-if="scope.row.status == '待接单'" effect="dark" type="warning">待接单</el-tag>
              <el-tag v-else effect="dark" type="danger">进行中</el-tag>
            </div>
          </template>
      
        </el-table-column>
        <el-table-column prop="type" label="工单类型" align="center">        
        </el-table-column>
        <el-table-column prop="address" label="操作" align="center">
          <template v-slot="scope">
            <div>
              <el-link @click="toEdit(scope.row)" :underline="false" type="success">详情</el-link>
              <el-link @click="toCancel(scope.row)" :underline="false" type="success">取消</el-link>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页开始 -->
    <div class="page" style="margin-top: 10px;">
      <el-pagination hide-on-single-page @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="params.page" :page-sizes="[5, 8, 10, 20]" :page-size="params.pageSize"
        layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>
    <!-- 分页结束 -->
    <el-drawer @close="reset" size="50%" :title="title" :visible.sync="visible" direction="rtl"
      custom-class="demo-drawer" ref="drawer">
      <div class="demo-drawer__content" style="padding-right: 10px;">
        <el-form ref="myForm" :model="formSave">
          <el-row>
            <el-col :span="12">
              <el-form-item prop="id" label="工单id" :label-width="formLabelWidth">
                <el-input class="input" v-model="formSave.id" autocomplete="off">
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="type" label="工单类型" :label-width="formLabelWidth">
                <el-input class="input" v-model="formSave.type" autocomplete="off">

                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="bill_why" label="问题叙述" :label-width="formLabelWidth">
                <el-input v-model="formSave.bill_why" autocomplete="off">
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="engineer_id" label="工程师编号" :label-width="formLabelWidth">
                <el-input v-model="formSave.engineer_id" autocomplete="off">
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="device_id" label="设备id" :label-width="formLabelWidth">
                <el-input v-model="formSave.device_id" autocomplete="off">

                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="account_id" label="账户id" :label-width="formLabelWidth">
                <el-input v-model="formSave.account_id" autocomplete="off">
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="create_time" label="创建时间" :label-width="formLabelWidth">
                <el-input v-model="formSave.create_time" autocomplete="off">
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="finish_time" label="完成时间" :label-width="formLabelWidth">
                <el-input v-model="formSave.finish_time" autocomplete="off">
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="finish_note" label="完成备注" :label-width="formLabelWidth">
                <el-input v-model="formSave.finish_note" autocomplete="off">
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="status" label="状态" :label-width="formLabelWidth">
                <el-input v-model="formSave.status" autocomplete="off">
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import { get } from '@/utils/request'
import moment from 'moment'
export default {
  data() {
    return {
      form: {
        device_name: ''
      },
      deviceData: [],
      params: {
        page: 1,
        pageSize: 5
      },
      total: 0,
      engData: [],
      title: '工程详情',
      visible: false,
      formSave: {},
      formLabelWidth: '90px',
    };
  },
  computed: {},
  methods: {
    toCancel(row) {
      this.$confirm('确定要取消该工单吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          // 假设接口需要工单ID作为参数
          const res = await get('/workorder/cancelOrder', { id: row.id });
          if (res.success) {
            this.$message({ type: 'success', message: '工单已成功取消!' });
            // 取消成功后重新获取数据
            this.getDevData();
          } else {
            this.$message({ type: 'error', message: res.message || '取消失败' });
          }
        } catch (error) {
          this.$message({ type: 'error', message: '操作失败，请重试' });
          console.error('取消工单失败:', error);
        }
      }).catch(() => {
        this.$message({ type: 'info', message: '已取消操作' });
      });
    },
    toEdit(row) {
      this.visible = true;
      this.title = '工程详情';
      this.formSave = _.clone(row);
      this.formSave.create_time = moment(this.formSave.create_time).format('YYYY-MM-DD HH:mm:ss');
      // this.formSave.finish_time = moment(this.formSave.finish_time).format('YYYY-MM-DD HH:mm:ss');
      if (row.finish_time) {
        const finishTime = moment(row.finish_time);
        this.formSave.finish_time = finishTime.isValid() ? finishTime.format('YYYY-MM-DD HH:mm:ss') : '';
      } else {
        this.formSave.finish_time = ''; // 无完成时间时显示空
      }
    },
    toSearch() {
      this.params.page = 1;
      this.getDevData();
    },
    async getDevData() {
      let temp = {
        ...this.form,
        ...this.params
      };
      let res = await get('/workorder/pageQuery', temp);
      this.deviceData = res.data.list;
    },
    reset() {
      this.$refs['myForm'].resetFields();
    },
    toSubmit() {
      this.$refs['myForm'].validate(async (valid) => {
        if (valid) {
          let data = _.clone(this.formSave);
          let res = await get('/workorder/findById', data);
        }
      });
    },

    handleSizeChange(val) {
      this.params.pageSize = val;  // 更新每页条数
      this.getDevData();           // 重新获取设备数据（而非工程数据）
    },
    handleCurrentChange(val) {
      this.params.page = val;      // 更新当前页码
      this.getDevData();           // 重新获取设备数据（而非工程数据）
    },

    // 2. 修复设备数据接口：赋值total总条数
    async getDevData() {
      const temp = { ...this.form, ...this.params };  // 合并查询条件和分页参数
      const res = await get('/workorder/pageQuery', temp);
      this.deviceData = res.data.list;  // 分页数据列表
      this.total = res.data.total;      // 关键：赋值总条数（用于分页计算）
    },
    async getEngData() {
      // 向接口传递分页参数（page：当前页，pageSize：每页条数）
      let res = await get('/engineer/pageQuery', this.params);
      // 从接口响应中提取「分页后的数据列表」和「总数据条数」
      this.engData = res.data.list;  // 表格要渲染的分页数据
      this.total = res.data.total;   // 总条数（用于分页组件计算总页数）
    },

    // 4. 删除操作后重置页码（确保删除后从第1页重新加载，避免页码超出范围）
    async toDelete(id) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        let res = await del('/engineer/deleteById', { id });
        this.$message({ type: 'success', message: '操作成功!' });
        this.params.page = 1;  // 删除后重置为第1页
        this.getEngData();     // 重新获取分页数据
      }).catch(() => {
        this.$message({ type: 'info', message: '已取消操作' });
      });
    },

  },
  created() {
    this.getDevData();
  },
  mounted() { },
};
</script>
<style lang="scss" scoped>
::v-deep .el-link--inner {
  margin-left: 5px;
}
</style>